package gzip

import (
	"compress/gzip"
	"duanju-mq/pkg/config"
	"io"
	"net/http"
	"strings"
)

var (
	fGzipThreshold = config.Int("gzip.threshold", 2048, "返回大于多少字节时开启gzip压缩")
	fGzipLevel     = config.Int("gzip.level", gzip.DefaultCompression, "gzip压缩等级")
)

func Write(w http.ResponseWriter, r *http.Request, b []byte) (int, error) {
	if len(b) > *fGzipThreshold && *fGzipLevel != gzip.NoCompression && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
		w.Header().Set("Content-Encoding", "gzip")
		gw, _ := gzip.NewWriterLevel(w, *fGzipLevel)
		defer gw.Close()
		return gw.Write(b)
	} else {
		return w.Write(b)
	}
}

func Writer(w http.ResponseWriter, r *http.Request) io.Writer {
	if *fGzipLevel != gzip.NoCompression && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
		w.Header().Set("Content-Encoding", "gzip")
		gw, _ := gzip.NewWriterLevel(w, *fGzipLevel)
		return gw
	} else {
		return w
	}
}
